import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, UserProfile, UserStats } from '@/types/user'
import { apiService } from '@/services/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const profile = ref<UserProfile | null>(null)
  const stats = ref<UserStats | null>(null)
  const isAuthenticated = ref(false)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const userRole = computed(() => user.value?.role || 'guest')
  const userName = computed(() => user.value?.username || '')
  const userEmail = computed(() => user.value?.email || '')
  const userAvatar = computed(() => profile.value?.avatar || '')
  const isAdmin = computed(() => userRole.value === 'admin')
  const isPremium = computed(() => userRole.value === 'premium')

  // 方法
  const login = async (email: string, password: string) => {
    loading.value = true
    error.value = null
    
    try {
      const result = await apiService.login(email, password)
      user.value = result.user
      isAuthenticated.value = true
      
      // 加载用户资料和统计信息
      await Promise.all([
        loadProfile(),
        loadStats()
      ])
      
      return result
    } catch (err: any) {
      error.value = err.message || '登录失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  const register = async (userData: {
    username: string
    email: string
    password: string
  }) => {
    loading.value = true
    error.value = null
    
    try {
      const result = await apiService.register(userData)
      user.value = result.user
      isAuthenticated.value = true
      
      // 加载用户资料和统计信息
      await Promise.all([
        loadProfile(),
        loadStats()
      ])
      
      return result
    } catch (err: any) {
      error.value = err.message || '注册失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  const logout = async () => {
    loading.value = true
    
    try {
      await apiService.logout()
    } catch (err) {
      console.error('Logout error:', err)
    } finally {
      user.value = null
      profile.value = null
      stats.value = null
      isAuthenticated.value = false
      loading.value = false
      error.value = null
    }
  }

  const loadProfile = async () => {
    if (!isAuthenticated.value) return
    
    try {
      profile.value = await apiService.getUserProfile()
    } catch (err: any) {
      console.error('Failed to load profile:', err)
      error.value = err.message || '加载用户资料失败'
    }
  }

  const updateProfile = async (updates: Partial<UserProfile>) => {
    if (!isAuthenticated.value) return
    
    loading.value = true
    error.value = null
    
    try {
      profile.value = await apiService.updateUserProfile(updates)
      
      // 如果更新了用户名，同时更新 user 对象
      if (updates.username && user.value) {
        user.value.username = updates.username
      }
      
      return profile.value
    } catch (err: any) {
      error.value = err.message || '更新用户资料失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  const changePassword = async (oldPassword: string, newPassword: string) => {
    loading.value = true
    error.value = null
    
    try {
      await apiService.changePassword(oldPassword, newPassword)
    } catch (err: any) {
      error.value = err.message || '修改密码失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  const loadStats = async () => {
    if (!isAuthenticated.value) return
    
    try {
      stats.value = await apiService.getUserStats()
    } catch (err: any) {
      console.error('Failed to load stats:', err)
      error.value = err.message || '加载用户统计失败'
    }
  }

  const getUserStats = async () => {
    await loadStats()
    return stats.value
  }

  const checkAuth = async () => {
    loading.value = true
    
    try {
      const currentUser = await apiService.getCurrentUser()
      user.value = currentUser
      isAuthenticated.value = true
      
      // 加载用户资料和统计信息
      await Promise.all([
        loadProfile(),
        loadStats()
      ])
      
      return currentUser
    } catch (err) {
      // 认证失败，清除状态
      user.value = null
      profile.value = null
      stats.value = null
      isAuthenticated.value = false
    } finally {
      loading.value = false
    }
  }

  const refreshToken = async () => {
    try {
      await apiService.refreshToken()
    } catch (err) {
      // Token 刷新失败，需要重新登录
      await logout()
      throw err
    }
  }

  const resetPassword = async (email: string) => {
    loading.value = true
    error.value = null
    
    try {
      // 这里应该调用重置密码的 API
      // await apiService.resetPassword(email)
      
      // 临时模拟
      await new Promise(resolve => setTimeout(resolve, 1000))
      
    } catch (err: any) {
      error.value = err.message || '重置密码失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  const clearError = () => {
    error.value = null
  }

  // 初始化
  const init = async () => {
    await checkAuth()
  }

  return {
    // 状态
    user,
    profile,
    stats,
    isAuthenticated,
    loading,
    error,
    
    // 计算属性
    userRole,
    userName,
    userEmail,
    userAvatar,
    isAdmin,
    isPremium,
    
    // 方法
    login,
    register,
    logout,
    loadProfile,
    updateProfile,
    changePassword,
    loadStats,
    getUserStats,
    checkAuth,
    refreshToken,
    resetPassword,
    clearError,
    init
  }
})